"""
这是一个socket简单的例子,这是客户端代码。
tcp和udp的区别：tcp连接发送数据不能一个个发送，而udp可以将数据一个个的发送给服务器。
"""
import socket
import time
import threading


class TCPClient:
    """ TCP发送客户端。"""

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
        self.s.connect((self.ip, self.port))
        self.t = threading.Thread(target=self.client)
        self.t.start()

    def client(self):
        while 1:
            self.s.send('tcp'.encode())
        s.close()


class UDPClient:
    """ UDP发送客户端。"""

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.s = socket.socket(type=socket.SOCK_DGRAM)
        t = threading.Thread(target=self.client)
        t.start()

    def client(self):
        # print(self.__class__.__name__, 'is running.')
        i = 0
        while 1:
            msg = str(i)
            self.s.sendto(msg.encode(), (self.ip, self.port))
            i += 1
            time.sleep(1)


class BroadcastClient:
    """ 广播发送客户端。"""

    def __init__(self, port):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        # self.ip = '<broadcast>'
        self.ip = '255.255.255.255'
        self.port = port

        # mytest = threading.Thread(target=self.send)
        # mytest.start()

    def send(self, msg):
        print(self.__class__.__name__, 'is running.')
        self.s.sendto(msg.encode('utf-8'), (self.ip, self.port))
        time.sleep(0.5)

